import re
import os


def convert_appium_recording_to_page_class(recording_code, class_name="TestPage", file_name=None):
    """
    将Appium Inspector录制的操作转换为page类文件
    
    :param recording_code: Appium Inspector录制的代码
    :param class_name: 生成的类名
    :param file_name: 保存的文件名（不包含.py扩展名）
    :return: 生成的文件路径
    """
    # 如果没有提供文件名，使用类名作为文件名
    if not file_name:
        file_name = "auto_case"
        
    # 获取项目根目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.dirname(current_dir)
    
    # 构建目标文件路径
    pages_dir = os.path.join(project_root, "pages")
    os.makedirs(pages_dir, exist_ok=True)
    target_file_path = os.path.join(pages_dir, f"{file_name}.py")
    
    # 解析录制的代码
    parsed_operations = _parse_recording_code(recording_code)
    
    # 生成类代码
    class_code = _generate_page_class(class_name, parsed_operations)
    
    # 写入文件
    with open(target_file_path, 'w', encoding='utf-8') as f:
        f.write(class_code)
    
    print(f"页面类文件已生成: {target_file_path}")
    return target_file_path


def _parse_recording_code(recording_code):
    """
    解析Appium Inspector录制的代码，提取操作信息
    
    :param recording_code: 录制的代码
    :return: 解析后的操作列表
    """
    operations = []
    
    # 分割代码为行
    lines = recording_code.strip().split('\n')
    
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        
        # 解析find_element操作
        if 'driver.find_element' in line and '=' in line:
            # 提取变量名
            var_match = re.match(r'(\w+)\s*=', line)
            var_name = var_match.group(1) if var_match else None
            
            # 提取定位方式和值
            by_match = re.search(r'by=AppiumBy\.(\w+)', line)
            by = by_match.group(1) if by_match else "ID"
            
            value_match = re.search(r'value=["\']([^"\']+)["\']', line)
            value = value_match.group(1) if value_match else ""
            
            # 查找后续的click/send_keys等操作
            i += 1
            while i < len(lines) and '=' not in lines[i] and lines[i].strip():
                next_line = lines[i].strip()
                
                # 解析click操作
                if '.click()' in next_line and var_name and var_name in next_line:
                    operations.append({
                        'type': 'click',
                        'by': by,
                        'value': value,
                        'var_name': var_name
                    })
                    break
                
                # 解析send_keys操作
                send_keys_match = re.search(r'\.send_keys\(["\']([^"\']*)["\']\)', next_line)
                if send_keys_match and var_name and var_name in next_line:
                    operations.append({
                        'type': 'send_keys',
                        'by': by,
                        'value': value,
                        'text': send_keys_match.group(1),
                        'var_name': var_name
                    })
                    break
                    
                # 解析clear操作
                if '.clear()' in next_line and var_name and var_name in next_line:
                    operations.append({
                        'type': 'clear',
                        'by': by,
                        'value': value,
                        'var_name': var_name
                    })
                    break
                    
                i += 1
            continue
            
        # 解析ActionChains操作
        elif 'ActionChains' in line:
            # 收集整个ActionChains块
            action_lines = []
            while i < len(lines) and lines[i].strip() != 'actions.perform()':
                if lines[i].strip():
                    action_lines.append(lines[i].strip())
                i += 1
            if i < len(lines):  # 添加perform()行
                action_lines.append(lines[i].strip())
                
            # 解析ActionChains操作
            action_operation = _parse_action_chains(action_lines)
            if action_operation:
                operations.append(action_operation)
                
        i += 1
    
    return operations


def _parse_action_chains(action_lines):
    """
    解析ActionChains操作块
    
    :param action_lines: ActionChains相关行
    :return: 解析后的操作字典
    """
    # 检查是否是滑动操作
    move_to_count = sum(1 for line in action_lines if 'move_to_location' in line)
    if move_to_count == 2 and any('pointer_down' in line for line in action_lines) and any('release' in line for line in action_lines):
        # 提取坐标
        coords = []
        for line in action_lines:
            coord_match = re.search(r'move_to_location\((\d+),\s*(\d+)\)', line)
            if coord_match:
                coords.append((int(coord_match.group(1)), int(coord_match.group(2))))
                
        if len(coords) == 2:
            return {
                'type': 'swipe',
                'start_x': coords[0][0],
                'start_y': coords[0][1],
                'end_x': coords[1][0],
                'end_y': coords[1][1]
            }
    
    # 检查是否是点击操作
    elif move_to_count == 1 and any('pointer_down' in line for line in action_lines) and any('release' in line for line in action_lines):
        # 提取坐标
        for line in action_lines:
            coord_match = re.search(r'move_to_location\((\d+),\s*(\d+)\)', line)
            if coord_match:
                return {
                    'type': 'tap',
                    'x': int(coord_match.group(1)),
                    'y': int(coord_match.group(2))
                }
    
    return None


def _generate_page_class(class_name, operations):
    """
    生成页面类代码
    
    :param class_name: 类名
    :param operations: 操作列表
    :return: 生成的类代码
    """
    # 导入语句
    imports = [
        "import time",
        "from appium.webdriver.common.appiumby import AppiumBy",
        "from base.base_page import find_and_do, press_keycode, switch_to_context, perform_touch_action, perform_swipe_sequence"
    ]
    
    import_block = "\n".join(imports)
    
    # 类定义
    class_def = f"class {class_name}:"
    
    # 初始化方法
    init_method = """    def __init__(self, driver):
        self.driver = driver"""
    
    # 测试方法
    test_method = "    def test_case(self):\n        driver = self.driver\n\n"
    
    # 操作列表
    operation_lines = []
    swipe_operations = []
    
    for i, op in enumerate(operations):
        if op['type'] == 'click':
            operation_lines.append(f"        find_and_do(driver, 'click', AppiumBy.{op['by']}, \"{op['value']}\")")
            operation_lines.append("        time.sleep(1)")
        elif op['type'] == 'send_keys':
            operation_lines.append(f"        find_and_do(driver, 'send_keys', AppiumBy.{op['by']}, \"{op['value']}\", \"{op['text']}\")")
            operation_lines.append("        time.sleep(1)")
        elif op['type'] == 'clear':
            operation_lines.append(f"        find_and_do(driver, 'clear', AppiumBy.{op['by']}, \"{op['value']}\")")
            operation_lines.append("        time.sleep(1)")
        elif op['type'] == 'swipe':
            swipe_operations.append({
                'start_x': op['start_x'],
                'start_y': op['start_y'],
                'end_x': op['end_x'],
                'end_y': op['end_y']
            })
        elif op['type'] == 'tap':
            # 点击操作转换为触摸动作
            operation_lines.append(f"        # 点击坐标 ({op['x']}, {op['y']})")
            operation_lines.append(f"        perform_touch_action(driver, [")
            operation_lines.append(f"            {{'type': 'move_to', 'x': {op['x']}, 'y': {op['y']}}},")
            operation_lines.append(f"            {{'type': 'pointer_down'}},")
            operation_lines.append(f"            {{'type': 'pause', 'duration': 0.1}},")
            operation_lines.append(f"            {{'type': 'pointer_up'}}")
            operation_lines.append(f"        ])")
            operation_lines.append("        time.sleep(1)")
    
    # 处理滑动操作
    if swipe_operations:
        operation_lines.append(f"\n        # 执行滑动操作")
        operation_lines.append(f"        swipes = [")
        for swipe in swipe_operations:
            operation_lines.append(f"            {{'start_x': {swipe['start_x']}, 'start_y': {swipe['start_y']}, 'end_x': {swipe['end_x']}, 'end_y': {swipe['end_y']}}},")
        operation_lines[-1] = operation_lines[-1][:-1]  # 移除最后一个逗号
        operation_lines.append(f"        ]")
        operation_lines.append(f"        perform_swipe_sequence(driver, swipes)")
        operation_lines.append("        time.sleep(1)")
    
    # 组合所有代码
    operation_block = "\n".join(operation_lines)
    test_method += operation_block
    
    # 组合完整类代码
    class_code = f"""{import_block}


{class_def}
{init_method}

{test_method}
"""
    
    return class_code


if __name__ == "__main__":
    # 示例用法，放appium inspector录制的操作路径
    recording_code = '''
el1 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/ivNext")
el1.click()
el1.click()
el1.click()
el2 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/stv_start")
el2.click()
el3 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/etEmail")
el3.send_keys("ypcna@q")
el4 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/llCode")
el4.click()
el5 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/etCode")
el5.send_keys("998877")
el6 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/cbAgreeOld")
el6.click()
el7 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/cbAgreePrivate")
el7.click()
el8 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/btnRegisterOrLogin")
el8.click()
el9 = driver.find_element(by=AppiumBy.ID, value="com.android.permissioncontroller:id/permission_allow_foreground_only_button")
el9.click()
el10 = driver.find_element(by=AppiumBy.ID, value="joyhub.net.joyhub:id/btn_video2")
el10.click()
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location(279, 1132)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.release()
actions.perform()

actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location(795, 1132)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.release()
actions.perform()

actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location(292, 1553)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.release()
actions.perform()

actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location(785, 1553)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.release()
actions.perform()

actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location(265, 2000)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.release()
actions.perform()

actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location(753, 1991)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.release()
actions.perform()


'''
    
    # 转换录制代码为页面类
    convert_appium_recording_to_page_class(recording_code, "Auto_case", "auto_case")